// pages/Shopbuying/index.js
// const md5 = require("../../../utils/md5.js");
import Toast from 'tdesign-miniprogram/toast/index';

const $api = require('../../../utils/request').Api;
const app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
    baseImgUrl: app.globalData.baseImgUrl,
    listdata: [],
    showDropdown: false,
		sum: 0,
		igowuche: '',
		danpinjiage: '',
		liangpinpu: [],
		shippingSpace: '',
		numopt: 1,
		itemYuanTotalPrice: '',
		coupon: null, // 当前选中的优惠券 id
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
  toggleDropdown: function() {
    this.setData({
      showDropdown: !this.data.showDropdown
    });
  },
	toUserVoucher () {
		wx.navigateTo({
			url: '/pages/Usevoucher/Usevoucher?price=' + this.data.sum,
			events: {
				selected: coupon => {
					this.setData({ coupon })
				}
			}
		})
	},
	onLoad(options) {
		console.log(options);
		let list = JSON.parse(options.data)
		console.log(list);
		this.setData({
			liangpinpu: options
		})

		if (options.index === '1') {
			this.data.igowuche = options.index
			// console.log('ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss');
			console.log(list);
			let opndata = []
			// let yunc = opndata.push(list)
			let numdata = ''
			// list.forEach(res => {
			// 	numdata = res.price + res.price
			// });
			console.log(numdata);
			this.setData({
				listdata: list,
				vin: options.data.vin||'1234567890' ,
				// shippingSpace: options.shippingSpace
				// sum: list[0].price === '' ? list[0].price : list[0].yprice
			})
			this.lianggeshuiangjia()
		} else if (options.index === '3') {
			this.data.igowuche = options.index
			// console.log('ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss');
			console.log(list);
			// let opndata = []
			// let yunc = opndata.push(list)
			// let numdata = ''
			// list.forEach(res => {
			// 	numdata = res.price + res.price
			// });
			console.log(options);
			if (list.length >= 1) {
				this.setData({
					listdata: list,
					vin: options.data.vin||'1234567890',
					sum: list[0].spzPrice === '' ? list[0].zongPrice : list[0].price,
					// shippingSpace: options.shippingSpace
					// sum: list[0].price === '' ? list[0].price : list[0].yprice
				})
			} else {
				this.setData({
					listdata: list,
					vin: options.data.vin||'1234567890',
					// shippingSpace: options.shippingSpace
					// sum: list[0].price === '' ? list[0].price : list[0].yprice
				})
			}

			this.lianggeshuiangjia()
		} else {
			// list[0].shippingSpace = options.shippingSpace
			console.log(list);
			if (list[0].price) {
				if (list[0].shippingSpace === undefined) {
					list[0].shippingSpace = options.shippingSpace
				}

				console.log(list);
				// let opnum = []
				// list.some((item, index) => {
				// 	opnum.push(item.yprice)
				// })
				// console.log(opnum);
				// let arrnum = function (nums) {
				// 	return nums.map(Number)
				// }
				// let sum = 0
				// let numdata = arrnum(opnum);

				// function t(value) {
				// 	sum += value;
				// }
				// numdata.forEach(t)
				// console.log(sum);
				// console.log(list[0].price === '' ? list[0].price : list[0].yprice);
				this.setData({
					listdata: list,
					vin: options.vin||'1234567890',
					sum: list[0].price === '' ? list[0].yprice : list[0].price,
					// shippingSpace: options.shippingSpace
				})
			} else {
				// list[0].shippingSpace = options.shippingSpace
				console.log(list);
				// let opnum = []
				// list.some((item, index) => {
				// 	opnum.push(item.price)
				// })
				// console.log(opnum);
				// let arrnum = function (nums) {
				// 	return nums.map(Number)
				// }
				// let sum = 0
				// let numdata = arrnum(opnum);

				// function t(value) {
				// 	sum += value;
				// }
				// numdata.forEach(t)
				// console.log(sum);
				this.setData({
					listdata: list,
					vin: options.vin||'1234567890',
					sum: list[0].price === '' ? list[0].price : list[0].yprice,
					// shippingSpace: options.shippingSpace
				})
			}
		}

	},
	numstepper(e) {
		console.log(e);
		this.setData({
			numopt: e.detail
		})
		// let numopt=e.detail
		let vin = wx.getStorageSync('vin')
		let login = wx.getStorageSync('login')
		console.log(e.currentTarget.dataset.lista);
		if (e.currentTarget.dataset.lista.productUrl) {
			console.log('ssssssssssssssss');
			wx.request({
				url: app.globalData.baseApiUrl +'/api/order/orderCalculate',
				method: 'POST',
				data: {
					vin: vin||'1234567890',
					num: e.detail,
					price: e.currentTarget.dataset.lista.price === '' ? e.currentTarget.dataset.lista.price : e.currentTarget.dataset.lista.yprice,
					productNumber: e.currentTarget.dataset.lista.productNumber,
					couponId: this.data.coupon?.id,
					memberNumber: login.data.data.memberNumber,
				},
				header: {
					'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
				},
				success: xite => {
					console.log(xite);
					this.setData({
						sum: xite.data.data.zongPrice,
						danpinjiage: xite.data.data.zongPrice,
						itemYuanTotalPrice: xite.data.data.itemYuanTotalPrice
					})

					// do something
				},
				fail: err => {}
			})
		} else {
			if (this.data.igowuche === '1') {
				let numdata = ''
				if (e.currentTarget.dataset.lista.activityStatus === '1') {
					numdata = e.currentTarget.dataset.lista.discountPrice
				} else {
					numdata = e.currentTarget.dataset.lista.price
				}
				wx.request({
					url: app.globalData.baseApiUrl +'/api/order/orderCalculate',
					method: 'POST',
					data: {
						vin: vin||'1234567890',
						num: e.detail,
						price: numdata,
						productNumber: e.currentTarget.dataset.lista.productNumber,
						couponId: this.data.coupon?.id,
						memberNumber: login.data.data.memberNumber,
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
					},
					success: xite => {
						console.log(xite);
						this.setData({
							sum: xite.data.data.zongPrice,
							// danpinjiage: xite.data.data.zongPrice
						})
						this.data.listdata.forEach((res, index) => {
							if (e.currentTarget.dataset.lista.cartId === res.cartId) {
								if (e.currentTarget.dataset.lista.activityStatus === '1') {
									res.discountPrice = xite.data.data.zongPrice
								} else {
									res.price = xite.data.data.zongPrice
								}
							}
						})
						this.setData({
							listdata: this.data.listdata
						})
						// do something
					},
					fail: err => {}
				})
				let add = []
				this.data.listdata.forEach((res, index) => {
					if (e.currentTarget.dataset.lista.cartId === res.cartId) {
						res.goodsNum = e.detail
					}
					add.push({
						price: res.price,
						num: res.goodsNum,
						vin: vin||'1234567890',
						productNumber: res.productNumber,
						cartId: res.cartId,
						shippingSpace: res.shippingSpace,
						memberNumber: login.data.data.memberNumber,
						goodsId:res.goodsId
					})
				})
				let lista = JSON.stringify(add)
				wx.request({
					url: app.globalData.baseApiUrl +'/api/shopping/updateCart',
					method: 'POST',
					data: {
						param: lista,
						vin: vin||'1234567890',
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
					},
					success: xite => {
						console.log(xite);
						this.setData({
							sum: xite.data.data.discountTotalPrices,
							// danpinjiage: xite.data.data.cartInfo[1].discountPrice
						})


						// do something
					},
					fail: err => {}
				})
			} else {
				wx.request({
					url: app.globalData.baseApiUrl +'/api/order/orderCalculate',
					method: 'POST',
					data: {
						vin: vin||'1234567890',
						num: e.detail,
						price: e.currentTarget.dataset.lista.price === '' ? e.currentTarget.dataset.lista.price : e.currentTarget.dataset.lista.yprice,
						productNumber: e.currentTarget.dataset.lista.productNumber,
						couponId: this.data.coupon?.id,
						memberNumber: login.data.data.memberNumber,
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
					},
					success: xite => {
						console.log(xite);
						this.setData({
							sum: xite.data.data.zongPrice,
							danpinjiage: xite.data.data.zongPrice,
							itemYuanTotalPrice: xite.data.data.itemYuanTotalPrice
						})
						// do something
					},
					fail: err => {}
				})
			}
		}

	},
	lianggeshuiangjia() {
		let vin = wx.getStorageSync('vin')
		let login = wx.getStorageSync('login')
		let add = []
		this.data.listdata.forEach((res, index) => {
			add.push({
				price: res.price,
				num: res.goodsNum,
				vin: vin||'1234567890',
				productNumber: res.productNumber,
				cartId: res.cartId,
				shippingSpace: res.shippingSpace,
				memberNumber: login.data.data.memberNumber,
				goodsId:res.goodsId
			})
		})
		let lista = JSON.stringify(add)
		wx.request({
			url: app.globalData.baseApiUrl +'/api/shopping/updateCart',
			method: 'POST',
			data: {
				param: lista,
				vin: vin||'1234567890',
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
			},
			success: xite => {
				console.log(xite);
				this.setData({
					sum: xite.data.data.discountTotalPrices
				})
				// do something
			},
			fail: err => {}
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	// onShareAppMessage() {

	// },
	onSubmit() {
		console.log(this.data.listdata);
		let login = wx.getStorageSync('login')
		let phon = wx.getStorageSync('userTel')
		let that = this
		console.log(this.data.listdata[0].yprice);
		let yunlist = []
		this.data.listdata.forEach((xitem, index) => {
			console.log(xitem);
			yunlist.push({
				goodsId: xitem.goodsId,
				productTitle: xitem.productTitle,
				price: xitem.price,
				num: this.data.numopt.toString(),
				conId: xitem.conId,
				productNumber: xitem.productNumber,
				// vin: this.data.vin
			})
		})
		let lop = JSON.stringify(yunlist)
		console.log(lop);

		wx.request({
			url: app.globalData.baseApiUrl +'/api/order/create',
			method: 'POST',
			data: {
				goodsInfo: lop.toString(),
				name: "微信用户",
				// num: this.data.numopt,
				// address: '',
				phone: phon.data,
				// productTitle: this.data.listdata[0].productTitle,
				zongPrice: +(this.data.sum - (this.data.coupon?.deduction_amount ?? 0)).toFixed(2),
				source: 2,
				// goodsId: this.data.listdata[0].goodsId,
				// productSize: this.data.listdata[0].productTitle,
				userId: login.data.data.memberNumber,
				vin: this.data.vin||'1234567890',
				couponId: this.data.coupon?.id,
				// conId: this.data.listdata[0].conId,
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
			},
			success: xite => {
				console.log(xite.data.code);
				if (xite.data.code === 1) {
					$api.yuzhifu({
						openid: login.data.data.openid,
						number: xite.data.data.number,
						pay: xite.data.data.pay,
						staff_no: xite.data.data.staff_no,
					}).then((item, index) => {
						console.log(item);
						// let timestamp = new Date().getTime();
						// console.log(timestamp);
						// console.log(this.getRandom());
						// var appinu = 'appId=' + res.data.appId + '&' + 'nonceStr=' + res.data.nonceStr + '&' + 'package=' + res.data.package + '&' + 'signType=' + res.data.signType + '&' + 'timeStamp=' + timestamp
						// this.getRandom()
						// let arr = appid + timeStamp + this.getRandom()
						// let jiami = md5.hex_md5(arr)
						wx.requestPayment({
							timeStamp: item.data.data.timeStamp,
							nonceStr: item.data.data.nonceStr,
							package: item.data.data.package,
							signType: item.data.data.signType,
							paySign: item.data.data.paySign,
							success(xitem) {
								console.log(xitem);
							},
							fail(xitem) {
								console.log(xitem);
								Toast({
									context: that,
									selector: '#t-toast',
									message: '支付失败请重试！',
								});
							}
						})
					})
				} else {
					Toast({
						context: that,
						selector: '#t-toast',
						message: xite.data.msg,
					});
				}
				// do something
			},
			fail: err => {}
		})
		// $api.orderCreate({
		// 	name: "",
		// 	num: 1,
		// 	address: '',
		// 	phone: phon.data,
		// 	productTitle: this.data.listdata[0].productTitle,
		// 	zongPrice: this.data.sum,
		// 	source: 2,
		// 	goodsId: this.data.listdata[0].goodsId,
		// 	productSize: this.data.listdata[0].productTitle,
		// 	userId: login.data.data.memberNumber,
		// 	vin: this.data.vin,
		// 	conId: this.data.listdata[0].conId,
		// 	goodsInfo: lop
		// }).then((res) => {
		// 	console.log(res);
		// 	if (res) {
		// 		$api.yuzhifu({
		// 			openid: login.data.data.openid,
		// 			number: res.data.data.number,
		// 			jine: res.data.data.jine,
		// 			staff_no: res.data.data.staff_no,
		// 		}).then((item, index) => {
		// 			console.log(item);
		// 			// let timestamp = new Date().getTime();
		// 			// console.log(timestamp);
		// 			// console.log(this.getRandom());
		// 			// var appinu = 'appId=' + res.data.appId + '&' + 'nonceStr=' + res.data.nonceStr + '&' + 'package=' + res.data.package + '&' + 'signType=' + res.data.signType + '&' + 'timeStamp=' + timestamp
		// 			// this.getRandom()
		// 			// let arr = appid + timeStamp + this.getRandom()
		// 			// let jiami = md5.hex_md5(arr)
		// 			wx.requestPayment({
		// 				timeStamp: item.data.data.timeStamp,
		// 				nonceStr: item.data.data.nonceStr,
		// 				package: item.data.data.package,
		// 				signType: item.data.data.signType,
		// 				paySign: item.data.data.paySign,
		// 				success(xitem) {
		// 					console.log(xitem);
		// 				},
		// 				fail(xitem) {
		// 					console.log(xitem);
		// 					Toast({
		// 						context: that,
		// 						selector: '#t-toast',
		// 						message: '支付失败请重试！',
		// 					});
		// 				}
		// 			})
		// 		})

		// 	}
		// })
	},
	getRandom() {
		var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
		var str_nums = "";
		for (var i = 0; i < 32; i++) {
			var id = parseInt(Math.random() * (arr.length - 1));
			str_nums += arr[id];
		}
		return str_nums;
	}
})
